<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="仓库类型:" prop="reType">
        <el-select v-model="query.reType" clearable placeholder="请选择">
          <el-option
            v-for="item in reTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称:" prop="storeId">
        <el-select v-model="query.storeId" filterable placeholder="请选择">
          <el-option
            v-for="item in WarehouseMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品类型:" prop="csmTypeSource">
        <el-tree-select
          v-model="query.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="状态:" prop="csmTypeSource">
        <el-select v-model="query.gdStatus" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in statusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式:" prop="csmTypeSource">
        <el-select v-model="query.sortBy" clearable filterable placeholder="请选择">
          <el-option label="总库存降序" :value="1" />
          <el-option label="总库存升序" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="editTablesSort"
        >编辑显示顺序</el-button>
        <el-checkbox v-model="query.filter" style="margin-left: 10px;" @change="checkboxChange">隐藏库存为0的商品</el-checkbox>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :immediate-fetch="false"
      custom-column
      @fetch="fetchData"
    />
    <list-sort ref="listSort" />
    <in-and-out ref="inAndOutStoreDetail" @storeDetail="storeDetail" />
    <store-detail ref="storeDetail" />
  </div>
</template>

<script>
  import {
    querystoreList,
    goodsTypeQueryList,
    queryStoreListAll
  } from '@/api'
  import { formatColumnMap } from '@/utils'
  import ListSort from './components/ListSort.vue'
  import InAndOut from './components/InAndOutStoreDetail'
  import StoreDetail from './components/StoreDetail'
  import getTreeData from '@/utils/jsonTree'

  export default {
    name: 'stockSearch',
    components: {
      ListSort, InAndOut, StoreDetail
    },
    data() {
      return {
        checked: '',
        goodsTypeMap: [],
        WarehouseMap: [],
        goodsTreeData: [],
        reTypeMap: [
          {
            value: 1,
            desc: '门市',
            key: 'SHOP'
          },
          {
            value: 3,
            desc: '气站',
            key: 'GASSTATION'
          },
          {
            value: 6,
            desc: '其他',
            key: 'OTHER'
          }
        ],
        bottleStatusMap: [
          { value: 1, desc: '重', key: 'HEAVY' },
          { value: 2, desc: '轻', key: 'LIGHT' },
          { value: 3, desc: '回收', key: 'RECYCLE' },
          { value: 4, desc: '故障', key: 'BROKEN' },
          { value: 5, desc: '已损坏', key: 'CORRUPT' },
          { value: 6, desc: '正常', key: 'NORMAL' },
          { value: 7, desc: '报废', key: 'SCRAPPED' },
          { value: 8, desc: '过期', key: 'EXPIRED' },
          { value: 9, desc: '问题重瓶', key: 'QUEHEAVY' }
        ],
        gdStatusMap: [
          { desc: '正常', value: 6 }
        ],
        statusMap: [
          { value: 1, desc: '重', key: 'HEAVY' },
          { value: 2, desc: '轻', key: 'LIGHT' },
          { value: 3, desc: '回收', key: 'RECYCLE' },
          { value: 4, desc: '故障', key: 'BROKEN' },
          { value: 5, desc: '已损坏', key: 'CORRUPT' },
          { value: 6, desc: '正常', key: 'NORMAL' },
          { value: 7, desc: '报废', key: 'SCRAPPED' },
          { value: 8, desc: '过期', key: 'EXPIRED' },
          { value: 9, desc: '问题重瓶', key: 'QUEHEAVY' }
        ],
        unitTypeMap: [
          { value: 1, desc: '只', key: 'ZHI' },
          { value: 2, desc: '公斤', key: 'KILOGRAM' },
          { value: 3, desc: '个', key: 'GE' },
          { value: 4, desc: '立方', key: 'CUBIC' },
          { value: 5, desc: '根', key: 'ROOT' },
          { value: 6, desc: '米', key: 'METER' },
          { value: 7, desc: '张', key: 'ZHANG' },
          { value: 8, desc: '把', key: 'BA' },
          { value: 9, desc: '条', key: 'TIAO' },
          { value: 10, desc: '盒', key: 'BOX' }
        ],
        orderSourceMap: [
          {
            value: 1,
            desc: '呼叫中心',
            key: 'PHONE'
          },
          {
            value: 2,
            desc: '微信',
            key: 'WEIXIN'
          },
          {
            value: 3,
            desc: '代客下单',
            key: 'SUSER'
          },
          {
            value: 4,
            desc: '门店',
            key: 'OTHER'
          },
          {
            value: 5,
            desc: '底座',
            key: 'DZ'
          }
        ],
        query: {
          reType: 1,
          filter: false,
          storeId: '',
          sortBy: ''
        },
        tag: '',
        reType: '',
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'gtName',
              label: '商品类型'
            },
            {
              prop: 'goodsName',
              width: 120,
              label: '商品名称'
            },
            {
              prop: 'goodsSpec',
              label: '规格型号'
            },
            {
              prop: 'unitId',
              align: 'center',
              label: '单位',
              render: (h, { row }) => (
              <span>
                {row.unitId &&
                  formatColumnMap(
                    this.unitTypeMap,
                    'value',
                    row.unitId,
                    'desc'
                  )}
              </span>
            )
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, { row }) => (
              <span>
                {row.gdStatus &&
                  formatColumnMap(
                    this.statusMap,
                    'value',
                    row.gdStatus,
                    'desc'
                  )}
              </span>
            )
            },
            {
              prop: 'carryCount',
              align: 'right',
              label: '期初',
              renderHeader: (h, scope) => {
                return (
                  <el-tooltip class='item' effect='dark' content={'注：当前库存是从上次结转时间' + this.tag + '开始计算'} placement='top-start'>
                      <i class='el-icon-question'> <span>期初</span></i>
                  </el-tooltip>
                )
              }
            },
            {
              prop: 'inCount',
              align: 'right',
              label: '入库',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.inAndOutStoreDetail(row, 1)}>{row.inCount}</el-link>
            },
            {
              prop: 'outCount',
              align: 'right',
              label: '出库',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.inAndOutStoreDetail(row, 2)}>{row.outCount}</el-link>
            },
            {
              prop: 'lessCount',
              align: 'right',
              label: '盘盈/亏'
            },
            {
              prop: 'gdCount',
              width: 120,
              align: 'right',
              label: '当前总库存',
              renderHeader: (h, scope) => {
                return (
                <el-tooltip class='item' effect='dark' content='期初+入库-出库+盘盈/亏=当前总库存=仓内库存+仓外库存' placement='top-start'>
                    <i class='el-icon-question'>当前总库存</i>
                </el-tooltip>
              )
              }
            },
            {
              prop: 'orgGdCount',
              align: 'right',
              label: '仓内库存',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.storeDetail(row)}>{row.orgGdCount}</el-link>
            },
            {
              prop: 'senderGdCount',
              align: 'right',
              label: '仓外库存',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.inAndOutStoreDetail(row, 3)}>{row.senderGdCount}</el-link>
            }
          ],
          data: []
        }
      }
    },
    watch: {
      'query.reType': function(newVal) {
        this.getWarehouseMap()
      }
    },
    async created() {
      this.initStste()
      this.getGoodsTreeData()
    },
    methods: {
      async initStste() {
        await this.getWarehouseMap()
        await goodsTypeQueryList().then(res => {
          this.goodsTypeMap = res.data
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (!this.query.reType) query.reType = 4
        const res = await querystoreList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.tag = res.data.tag
      },
      checkboxChange(value) {
        this.query.filter = value
        this.$refs.lbTable.fetch()
      },
      async editTablesSort() {
        const row = this.tableData.data
        if (row.length === 0) {
          return
        }
        await this.$refs.listSort.open(row)
        this.$refs.lbTable.fetch()
      },
      async inAndOutStoreDetail(row, type) {
        await this.$refs.inAndOutStoreDetail.open(row, type)
      },
      async storeDetail(row) {
        await this.$refs.storeDetail.open(row)
      },
      getWarehouseMap() {
        const reType = this.query.reType || 4
        queryStoreListAll({ reType }).then(res => {
          this.WarehouseMap = res.data
          this.query.storeId = res.data[0].storeId
          this.fetchData({ currentPage: 1, pageSize: 20 })
        })
      },
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map((item) => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data, 'parentId', 'gtId')
      },
      // 选择商品分类
      async selectTreeChange(value) {
        if (value.gtId === 0 || (value.gtFlag && value.gtFlag < 3)) {
          if (this.statusMap !== this.bottleStatusMap) {
            this.query.gdStatus = ''
            this.statusMap = this.bottleStatusMap
          }
        } else {
          if (this.statusMap !== this.gdStatusMap) {
            this.query.gdStatus = ''
            this.statusMap = this.gdStatusMap
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped></style>
